package com.zhoug.player.core.utils;

import android.view.View;
import android.view.View.MeasureSpec;


import com.zhoug.player.core.ZPlayer;

import androidx.annotation.NonNull;

/**
 * @Author: zhoug
 * @Date: 2023/1/19
 * @Description:
 */
public class VideoSizeHelper {
    private float mVideoRatio = 0;//视频的宽高比
    /**
     * 显示模式
     * {@link ZPlayer#RENDER_MODE_FULL_FILL_SCREEN,ZPlayer#RENDER_MODE_ADJUST_RESOLUTION}
     */
    private int mRenderMode = ZPlayer.RENDER_MODE_FULL_FILL_SCREEN;
    /**
     * 视频和显示控件的宽高比之差小于这个值则不重新计算宽高
     */
    private static final float MAX_ASPECT_RATIO_DEFORMATION_FRACTION = 0.01f;

    private View mTargetView;

    public VideoSizeHelper(@NonNull View targetView) {
        this.mTargetView = targetView;
    }

    public void setRatio(float ratio) {
        if (mVideoRatio != ratio) {
            this.mVideoRatio = ratio;
            mTargetView.requestLayout();
        }
    }

    /**
     * 设置显示模式
     * {@link ZPlayer#RENDER_MODE_ADJUST_RESOLUTION} 自适应模式：视频画面将等比例缩放，会居中显示，此模式可能会有黑边
     * {@link ZPlayer#RENDER_MODE_FULL_FILL_SCREEN} 平铺模式：视频画面将会按照比例铺满屏幕，多余部分会被裁减掉，此模式下不会有黑边。
     *
     * @param renderMode
     */
    public void setRenderMode(int renderMode) {
        if (mRenderMode != renderMode) {
            this.mRenderMode = renderMode;
            mTargetView.requestLayout();
        }
    }

    /**
     *
     * @return int[2] widthMeasureSpec,heightMeasureSpec
     */
    public int[] onMeasure() {
        if (mVideoRatio <= 0) return null;
        int measuredWidth = mTargetView.getMeasuredWidth();
        int measuredHeight = mTargetView.getMeasuredHeight();
        float viewRatio = measuredWidth * 1.0f / measuredHeight;
        if (Math.abs(mVideoRatio - viewRatio) <= MAX_ASPECT_RATIO_DEFORMATION_FRACTION) {
            return null;
        }
        if (mRenderMode == ZPlayer.RENDER_MODE_ADJUST_RESOLUTION) {
            if (viewRatio > mVideoRatio) {
                measuredWidth = (int) (measuredHeight * mVideoRatio);
            } else {
                measuredHeight = (int) (measuredWidth / mVideoRatio);
            }
        } else {
            if (viewRatio < mVideoRatio) {
                measuredWidth = (int) (measuredHeight * mVideoRatio);
            } else {
                measuredHeight = (int) (measuredWidth / mVideoRatio);
            }
        }
        int[] measureSpecs = new int[2];
        measureSpecs[0] = MeasureSpec.makeMeasureSpec(measuredWidth, MeasureSpec.EXACTLY);
        measureSpecs[1] = MeasureSpec.makeMeasureSpec(measuredHeight, MeasureSpec.EXACTLY);
        return measureSpecs;
    }


}
